package com.tianji.aigc.tools;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.tianji.aigc.config.ToolResultHolder;
import com.tianji.aigc.constants.Constant;
import com.tianji.aigc.tools.result.CourseInfo;
import com.tianji.api.client.course.CourseClient;
import lombok.AllArgsConstructor;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.util.Optional;


@Component
@AllArgsConstructor
public class CourseTools {

    private final CourseClient courseClient;

    // 提取格式字符串常量
    private static final String FIELD_NAME_FORMAT = "{}_{}";

    /**
     * 根据课程id查询课程信息
     * @param courseId
     * @return
     */
    @Tool(description = Constant.Tools.QUERY_COURSE_BY_ID)
    public CourseInfo queryCourseById(@ToolParam(description = Constant.ToolParams.COURSE_ID) Long courseId,
                                      ToolContext toolContext){

       return Optional.ofNullable(courseId)
               .map(id -> this.courseClient.baseInfo(id,true))
               .map(CourseInfo::of)
               .map(courseInfo -> {
                   //存储数据的字段名  例如 ：courseInfo_1589905661084430337 全类名首字母小写_课程id
                   String field = StrUtil.format(FIELD_NAME_FORMAT,
                           StrUtil.lowerFirst(CourseInfo.class.getSimpleName()),
                           courseId);
                   //存储的key 例如 1589905661084430337 课程id
                 //  var requestId = Convert.toStr(toolContext.getContext().get(Constant.REQUEST_ID));
                   var requestId = MapUtil.get(toolContext.getContext(), Constant.REQUEST_ID, String.class);
                   ToolResultHolder.put(requestId,field,courseInfo);
                   return courseInfo;

               })
               .orElse(null);

    }

}
